//
//  MessageRequestModel.m
//  ExcellentHome
//
//  Created by Wendy on 16/7/26.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "MessageDataBaseModel.h"
#import "MessageRequestModel.h"
#import "SEGMessageUserModel.h"

@implementation MessageRequestModel
/**
 *  单例统一管理Message涉及的网络请求
 *
 *  @return MessageRequestModel
 */
+ (instancetype)sharedRequestModel
{
    static MessageRequestModel* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });

    return instance;
}

/*==========用于NewMyMessageRootViewController==========*/
/**
 *  请求消息列表
 *
 *  @param finished 网络请求完成后的操作
 */
- (void)requestMessageList:(SEGNetworkReponse)finished
{
    SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
    NSDictionary* params = @{
                             @"provinceId":account.provinceId,
                             @"cityId":account.cityId
                             };

    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/msg/getMsgV3",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, result, codeType, errorMessage);
            return;
        }
        
        NSArray* arr = [result valueForKey:@"data"];
        if ((!arr) || (![arr isKindOfClass:[NSArray class]])) {
            finished(NO, result, codeType, errorMessage);
            return;
        }
        
        NSMutableArray *failedArr = [NSMutableArray array];
        for (NSDictionary* dictt in arr) {
            //保存消息
            BOOL ss = [[MessageDataBaseModel sharedDataBaseModel] saveMessageWithDictionary:dictt];
            if(!ss) {//多次重复插入还没有成功 保存起来
                [failedArr addObject:dictt];
            }
        }
        
        NSArray *currentArr = [[MessageDataBaseModel sharedDataBaseModel] getArchiveMessageArray];;
        NSMutableArray *totalArr = [NSMutableArray arrayWithArray:currentArr];
        [failedArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            __block BOOL isContain = NO;
            [totalArr enumerateObjectsUsingBlock:^(NSDictionary *obj1, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"messageId"] isEqualToString: obj1[@"messageId"]]) {
                    isContain = YES;
                    *stop = YES;
                }
            }];
            if (!isContain) {
                [totalArr addObject:obj];
            }
        }];
        
        if (totalArr.count > currentArr.count) {
            //归档
            [[MessageDataBaseModel sharedDataBaseModel] archiveMessageArray:totalArr];
        }
        
        finished(YES, result, codeType, errorMessage);
        
    }];
}


///*==========用于SEGOrderMessageViewController==========*/

/**
 *  请求服务到家订单详情
 *
 *  @param providerSid   参数providerSid
 *  @param finished 网络请求完成后的操作
 */
- (void)requestProviderDetailWithProviderSid:(NSString*)providerSid finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:providerSid, @"providerSid", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-app/homeservice-api/v1/provider/detail.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 *  请求信息强推（订单详情页使用）
 *
 *  @param params   参数params字典
 *  @param finished 网络请求完成后的操作
 */
- (void)requestPushMessageWithParamsDict:(NSDictionary*)params finished:(SEGNetworkReponse)finished
{
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/message/privateChat",nil];
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST
                                            URLString:urlString
                                           parameters:params
                                             finished:^(BOOL isSuccessed,
                                                        id result,
                                                        NSString *codeType,
                                                        NSString *errorMessage) {
                                                 finished(isSuccessed, result, codeType, errorMessage);
                                             }];
    
}

/*==========用于SessionMessageViewController==========*/
/**
 *  请求信息强推
 *
 *  @param finished 网络请求完成后的操作
 */
- (void)requestPushMessageForChat:(NSString*)msgType contentType:(NSString*)contentType userId:(NSString*)userId title:(NSString*)title description:(NSString*)description content:(NSString*)content type:(NSString*)type serviceId:(NSString*)serviceId from:(NSString*)from groupId:(NSString*)groupId provider:(NSString*)provider finished:(SEGNetworkReponse)finished
{
#warning 优化，合并requestPushMessageForChat和requestPushMessageWithParamsDict
    int msg = [msgType intValue];
    int cot = [contentType intValue];
    NSDictionary* dic = nil;
    if ([type isEqualToString:kMessageTypeHomeService]) {
        dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:msg], @"msgType", [NSNumber numberWithInt:cot], @"contentType", userId, @"userId", title, @"title", description, @"description", content, @"content", type, @"type", serviceId, @"serviceId", from, @"from", groupId, @"groupId", provider, @"provider", nil];
    }
    else {
        dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:msg], @"msgType", [NSNumber numberWithInt:cot], @"contentType", userId, @"userId", title, @"title", description, @"description", content, @"content", type, @"type", serviceId, @"serviceId", from, @"from", nil];
    }

    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/message/privateChat",nil];
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST
                                            URLString:urlString
                                           parameters:dic
                                             finished:^(BOOL isSuccessed,
                                                        id result,
                                                        NSString *codeType,
                                                        NSString *errorMessage) {
                                                 finished(isSuccessed, result, codeType, errorMessage);
                                             }];
}

#pragma mark - 4.3.7新增
/**
 *  请求用户信息
 *
 *  @param ids   用户的Id
 *  @param finished 网络请求完成后的操作
 */
- (void)requestUserMessageWithUsersId:(NSString*)ids finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:ids, @"ids", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/bms-api/message/userMessage",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST
                                        URLString:urlString
                                       parameters:params
                                         finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {

        if (isSuccessed) {
            NSDictionary *dict = [result objectForKey:@"data"];
            self.userInfoDict = [NSMutableDictionary dictionary];
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[NSDictionary class]]) {
                    SEGMessageUserModel *model = [SEGMessageUserModel initWithDictionary:obj];
                    [self.userInfoDict setValue:model forKey:key];
                }
            }];
        }else {
            self.userInfoDict = [NSMutableDictionary dictionary];
        }

        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 *  请求服务号基本信息
 *
 *  @param finished 网络请求完成后的操作
 */
- (void)requestServicenbrBaseInfo:(SEGNetworkReponse)finished
{
    NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:kAccountCommunityID, @"communityId", nil];

    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/bms-api/servicenbr/baseInfo",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            NSDictionary *dict = [result objectForKey:@"data"];
            self.serviceBaseInfoModel = [SEGServiceBaseInfoModel yy_modelWithDictionary:dict];
        }else {
            self.serviceBaseInfoModel = [[SEGServiceBaseInfoModel alloc] init];
        }
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/*
 *  请求服务号底部菜单接口
 *
 *  @param serviceNbr   服务号
 *  @param serviceNumberId  服务号主键Id
 *  @param communityId   项目Id
 *  @param finished 网络请求完成后的操作
 *  @author Helen
 */
-(void)requestServicenbrMenuListWithServiceNbr:(NSString *)serviceNbr
                               serviceNumberId:(NSString *)serviceNumberId
                                   communityId:(NSString *)communityId
                                      finished:(SEGNetworkReponse)finished{
    // 3. 网路请求方法(必须添加)
    NSDictionary* params = @{
                             @"serviceNbr" : serviceNbr,
                             @"serviceNumberId" : serviceNumberId,
                             @"communityId" : communityId
                             };

    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/bms-api/servicenbr/menuList",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            NSArray *arrayData = [result objectForKey:@"data"];
            
            NSMutableArray *arrM = [NSMutableArray array];
            for (NSDictionary* dict in arrayData) {
                SEGMenuListModel *menuListModel = [SEGMenuListModel yy_modelWithJSON:dict];
                [arrM addObject:menuListModel];
            }
            self.servicenbrMenuListModel = arrM;
        }else {
            self.servicenbrMenuListModel = [NSArray array];
        }
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/*
 *  请求中奖公告详情
 *
 *  @param noticeId   中奖公告ID
 *  @param finished 网络请求完成后的操作
 *  @author Helen
 */
-(void)requestWinningPublicDetailWithObjId:(NSString *)noticeId
                                  finished:(SEGNetworkReponse)finished
{
    NSDictionary* params = @{
                             @"noticeId" : noticeId,
                             @"userId" : kAccountUserID
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/notice/appNoticeDetails",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            NSDictionary *data = [result objectForKey:@"data"];
            if (data && [data isKindOfClass:[NSDictionary class]]) {
                SEGWinningPublicModel *model = [SEGWinningPublicModel yy_modelWithJSON:data];
                self.winningPublicModel = model;
            }
        }
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

#pragma mark ----------------------- getter
- (NSArray<SEGMenuListModel*>*)servicenbrMenuListModel
{
    if (!_servicenbrMenuListModel)
    {
        _servicenbrMenuListModel = [NSArray array];
    }
    return _servicenbrMenuListModel;
}

- (SEGWinningPublicModel *)winningPublicModel
{
    if (!_winningPublicModel) {
        _winningPublicModel = [[SEGWinningPublicModel alloc] init];
    }
    return _winningPublicModel;
}

@end
